//
//  KVCustomComboBox.m
//  KVComboBoxDemo
//
//  Created by oupeng on 17/2/13.
//  Copyright © 2017年 oupeng. All rights reserved.
//

#import "KVCustomComboBox.h"
#import <Masonry.h>

// 水平间距
#define kHSpace             5

@interface KVCustomComboBox ()<NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate>

@end

@implementation KVCustomComboBox {
    __weak IBOutlet NSView          *comboBoxView;
    __weak IBOutlet NSTextField     *textField;
    __weak IBOutlet NSButton        *upDownBtn;
    __weak IBOutlet NSScrollView    *listContainer;
    __weak IBOutlet NSTableView     *listView;
    
    NSUInteger                      currentIndex; /**< 当前选择的下标 */
}

-(void)awakeFromNib {
    [super awakeFromNib];
    [self layoutSubViews];
    [self initConfigure];
}

#pragma mark -- Custom Methods
// 布局子视图
-(void)layoutSubViews {
    [self setFrame:NSMakeRect(0, 0, kComboBoxWidth, kComboBoxHeight*5)];
    
    [comboBoxView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self);
        make.height.equalTo(@kComboBoxHeight);
    }];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(comboBoxView).offset(kHSpace);
        make.width.equalTo(@(kComboBoxWidth - kComboBoxHeight - 2*kHSpace));
        make.height.mas_lessThanOrEqualTo(comboBoxView);
        make.centerY.equalTo(comboBoxView);
    }];
    
    [upDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(textField.mas_right).offset(kHSpace);
        make.top.equalTo(comboBoxView);
        make.size.mas_equalTo(NSMakeSize(kComboBoxHeight, kComboBoxHeight));
    }];
    
    [listContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self);
        make.top.equalTo(comboBoxView.mas_bottom);
        make.size.mas_equalTo(NSMakeSize(kComboBoxWidth, kComboBoxHeight*4));
    }];
    
    [listView setFrame:NSMakeRect(0, 0, kComboBoxWidth-4*kHSpace, kComboBoxHeight*4)];
    
    [listView setAllowsColumnResizing:YES];
    [listContainer setDocumentView:listView];
    [listContainer setHasHorizontalScroller:NO];
//    [listContainer setHasVerticalScroller:NO];
    
    listView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleNone; // 选择不变色
    
    [listView setDelegate:self];
    [listView setDataSource:self];
    listView.headerView = nil;
}

// 初始化默认配置
-(void)initConfigure {
    
    listContainer.hidden = YES;
    
    textField.delegate = self;
    textField.bordered = NO;
    textField.font = [NSFont systemFontOfSize:18.f];
    
    comboBoxView.wantsLayer = YES;
    comboBoxView.layer.borderWidth = 1.f;
    comboBoxView.layer.borderColor = [NSColor redColor].CGColor;
    comboBoxView.layer.backgroundColor = [NSColor whiteColor].CGColor;
    
    self.dataList = [NSMutableArray new];
    self.currentValue = [NSMutableString new];
}

- (IBAction)onClickUpDownBtn:(id)sender {
    listContainer.hidden = !listContainer.isHidden;
    [self updateUpDownBtn];
}

//返回行数
-(NSInteger) numberOfRowsInTableView:(NSTableView *)tableView {
    return self.dataList.count;
}

//每个单元内的view
-(NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
    NSTextField *label = [[NSTextField alloc] init];
    label.bordered = NO;
    label.editable = NO;
    label.font = [NSFont systemFontOfSize:18.f];
        label.backgroundColor = [NSColor clearColor];
    label.stringValue = [[self dataListToSecureTextOrNot] objectAtIndex:row];
    
    NSButton *deleteBtn = [[NSButton alloc] initWithFrame:NSMakeRect(kComboBoxWidth - 20 - 4*kHSpace, 5, 20, 20)];
    deleteBtn.tag = row;
    
    deleteBtn.bezelStyle = NSBezelStyleInline;
    deleteBtn.title = @"X"; // ╳
    
    [deleteBtn setTarget:self];
    [deleteBtn setAction:@selector(onClickDeleteBtn:)];
    
    NSView *cellView = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, kComboBoxWidth - kComboBoxHeight - 5*kHSpace, kComboBoxHeight)];
    [cellView addSubview:label];
    [cellView addSubview:deleteBtn];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cellView);
        make.left.equalTo(cellView);
        make.width.equalTo(@(kComboBoxWidth - kComboBoxHeight - 5*kHSpace));
    }];
    
    cellView.wantsLayer = YES;
//    cellView.layer.backgroundColor = [NSColor redColor].CGColor;
    [cellView addTrackingRect:[cellView bounds] owner:self userData:(void *)[NSString stringWithFormat:@"%ld", (long)row] assumeInside:NO];
    
    return cellView;
}
// 行高
-(CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return kComboBoxHeight;
}
// 是否可以选中单元格
-(BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row {
    [tableView deselectRow:row];
    currentIndex = row;
    return YES;
}
// 选中的响应
-(void)tableViewSelectionDidChange:(nonnull NSNotification *)notification {
    [listView deselectRow:currentIndex];
    [self onClickCell];
}

// 鼠标移入
-(void)mouseEntered:(NSEvent *)theEvent {
    NSString *stringID = (NSString *)[theEvent userData];
    NSView *cellView = [listView viewAtColumn:0 row:[stringID integerValue] makeIfNecessary:NO];
    cellView.layer.backgroundColor = [NSColor greenColor].CGColor;
    NSLog(@"mouseEctered : %@", stringID);
}

// 鼠标移除
-(void) mouseExited:(NSEvent *)theEvent {
    NSString *stringID = (NSString *)[theEvent userData];
    NSView *cellView = [listView viewAtColumn:0 row:[stringID integerValue] makeIfNecessary:NO];
    cellView.layer.backgroundColor = [NSColor clearColor].CGColor;
    NSLog(@"Exit : %@", stringID);
}

// 鼠标
-(void)mouseDown:(NSEvent *)event {
    
}

// 点击cell
-(void)onClickCell {
    listContainer.hidden = YES;
    [self updateUpDownBtn];
    _currentValue = [_dataList objectAtIndex:currentIndex];
    textField.stringValue = _currentValue;
    
    [self performSelector:@selector(changeToSecureTextOrNot) withObject:nil afterDelay:0.0f];
}

-(void)updateUpDownBtn {
    if ( !listContainer.hidden ) {
        [upDownBtn setImage:[NSImage imageNamed:@"icon_arrow_up"]];
    } else {
        [upDownBtn setImage:[NSImage imageNamed:@"icon_arrow_down"]];
    }
}

// 点击cell删除按钮
-(void)onClickDeleteBtn:(NSButton *)button {
    NSInteger index = button.tag;
    [self deleteDataAtIndex:index];
}

#pragma mark -- seter
-(void)setTextFont:(NSFont *)textFont {
    _textFont = textFont;
    textField.font = _textFont;
}

-(void)setTextColor:(NSColor *)textColor {
    _textColor = textColor;
    textField.textColor = _textColor;
}

-(void)setTextBgColor:(NSColor *)textBgColor {
    _textBgColor = textBgColor;
    textField.backgroundColor = _textBgColor;
}

-(void)setTextBordered:(BOOL)textBordered {
    _textBordered = textBordered;
    textField.bordered = _textBordered;
}

-(void)setTextSecure:(BOOL)textSecure {
    _textSecure = textSecure;
    [self changeToSecureTextOrNot];
    [listView reloadData];
}

-(void)setListFont:(NSFont *)listFont {
    _listFont = listFont;
    [listView reloadData];
}

-(void)setListColor:(NSColor *)listColor {
    _listColor = listColor;
    [listView reloadData];
}

-(void)setListBgColor:(NSColor *)listBgColor {
    _listBgColor = listBgColor;
    [listView reloadData];
}

-(void)setHasDeleteBtn:(BOOL)hasDeleteBtn {
    _hasDeleteBtn = hasDeleteBtn;
    [listView reloadData];
}

-(void)setCurrentValue:(NSMutableString *)currentValue {
    _currentValue = currentValue;
    [self changeToSecureTextOrNot];
}

-(void)setDataList:(NSMutableArray *)dataList {
    _dataList = dataList;
    [listView reloadData];
}

#pragma mark -- Custom Methods
-(void)addData:(NSString *)data {
    // 如果存在
    if ( [_dataList containsObject:data] ) return;
    [_dataList addObject:data];
    [listView reloadData];
}

-(void)deleteDataAtIndex:(NSUInteger)index {
    
    // 如果当前值就是要删除的值
    if ( [_currentValue isEqualToString:[_dataList objectAtIndex:index]] ) {
        _currentValue = [[NSMutableString alloc] initWithString:@""];
        [self changeToSecureTextOrNot];
    }
    
    [_dataList removeObjectAtIndex:index];
    [listView reloadData];
}

-(void)deleteAllData {
    [_dataList removeAllObjects];
    [listView reloadData];
}

-(void)changeToSecureTextOrNot {
    
    // 如果明文显示
    if ( !self.textSecure ) {
        textField.stringValue =  _currentValue;
        return;
    }
    
    NSUInteger length = _currentValue.length;
    NSMutableString *retStr = [NSMutableString new];
    
    for (int ix = 0; ix < length; ix++) {
        [retStr appendString:@"*"];
    }
    
    textField.stringValue =  retStr;
}

-(NSArray *)dataListToSecureTextOrNot {
    
    // 如果显示明文
    if ( !self.textSecure ) {
        return _dataList;
    }
    
    NSMutableArray *retList = [NSMutableArray new];
    
    for (NSString *strValue in _dataList) {
        // 获取需要替换的范围
        NSRange range = NSMakeRange(3, strValue.length - 7);
        
        // 如果存在
        if ( range.location != NSNotFound ) {
            // 字符串替换
            NSString *infoStr = [strValue stringByReplacingCharactersInRange:range withString:@"*****"];
            [retList addObject:infoStr];
        }
    }
    
    return retList;
}

#pragma mark -- NSTextFieldDelegate
-(void)controlTextDidChange:(NSNotification *)obj {
    NSComboBox *box = obj.object;
    NSString *tmpStr = box.stringValue;
    
    // 如果是全部删除
    if ( tmpStr.length <= 0 ) {
        _currentValue = [NSMutableString new];
    } else if ( tmpStr.length < _currentValue.length ) {
        // 删除一个字符
        [_currentValue deleteCharactersInRange:NSMakeRange(_currentValue.length - 1, 1)];
    } else if ( tmpStr.length > _currentValue.length ) {
        // 输入的一个字符
        NSString *last = [tmpStr substringFromIndex:tmpStr.length - 1];
        _currentValue = [[NSMutableString alloc] initWithString:[_currentValue stringByAppendingString:last]];
    } else {
        // nothing
    }
    
    // 延时0.5s变密文
    [self performSelector:@selector(changeToSecureTextOrNot) withObject:nil afterDelay:0.5f];
}

@end
